<template>
  <div class="table-content" v-if="showMain">
    <el-table :data="form.table" highlight-current-row fit class="table-form" :key="refreshKey" height="calc(100vh - 220px)">
      <el-table-column label="字段名称" show-overflow-tooltip min-width="150">
        <template v-slot:default="scope">
          <span v-model="scope.row.COLUMN_NAME">{{ scope.row.COLUMN_NAME }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字段类型" width="150" show-overflow-tooltip>
        <template v-slot:default="scope">
          <span>{{ scope.row.COLUMN_TYPE }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字段注释" show-overflow-tooltip min-width="150">
        <template v-slot:default="scope">
          <div style="text-decoration:none;cursor:pointer;" v-if="scope.row.COLUMN_COMMENT">
            {{ scope.row.COLUMN_COMMENT }}
          </div>
          <div v-else> -</div>
        </template>
      </el-table-column>
      <el-table-column label="能为NULL" show-overflow-tooltip width="100" v-if="dbInfo.dbType === 'mysql'">
        <template v-slot:default="scope">
          <div style="text-decoration:none;cursor:pointer;" v-if="scope.row.IS_NULLABLE">
            <span>{{ scope.row.IS_NULLABLE }}</span>
          </div>
          <div v-else> -</div>
        </template>
      </el-table-column>
      <el-table-column label="列键" show-overflow-tooltip width="80" v-if="dbInfo.dbType === 'mysql'">
        <template v-slot:default="scope">
          <div style="text-decoration:none;cursor:pointer;" v-if="scope.row.COLUMN_KEY">
            {{ scope.row.COLUMN_KEY }}
          </div>
          <div v-else> -</div>
        </template>
      </el-table-column>
      <el-table-column label="字段关联" width="140" show-overflow-tooltip >
        <template v-slot:default="scope">
          <div class="" v-if="scope.row.FAKER || scope.row.VALUE">
            不关联
          </div>
          <div class="" v-else-if="scope.row.contactTable">
            关联其他表字段
          </div>
          <div class="" v-else-if="scope.row.copyCurrentField">
            关联当前表字段
          </div>
          <div class="" v-else-if="scope.row.fileName">
            关联文件
          </div>
          <div v-else> -</div>
        </template>
      </el-table-column>
      <el-table-column label="字段生成规则" min-width="150" :show-overflow-tooltip='true'>
        <template v-slot:default="scope">
          <div class="rule" v-if="scope.row.FAKER">
<!--            <span v-if="scope.row.VALUE">【</span>-->
            <span>{{ scope.row.FAKER ? valueToLabel(1, scope.row.FAKER[0], scope.row.FAKER[1]) : "" }}</span>
<!--            <span v-if="scope.row.VALUE">】</span>-->
<!--            {{ scope.row.VALUE ? valueToLabel(2, scope.row.VALUE, "") : "" }}-->
          </div>
          <div class="rule" v-else-if="scope.row.VALUE">
            <span>{{ scope.row.VALUE }}</span>
          </div>
          <div class="rule" v-else-if="scope.row.contactTable">
            <span>{{ scope.row.contactTable }}/{{ scope.row.contactColumn }}</span>
          </div>
          <div class="rule" v-else-if="scope.row.copyCurrentField">
            <span>{{ scope.row.copyCurrentField }}</span>
          </div>
          <div class="rule" v-else-if="scope.row.fileName">
            <span>{{ scope.row.fileName }}</span>
          </div>
          <div v-else> -</div>
        </template>
      </el-table-column>
      <el-table-column label="参数值" min-width="150" :show-overflow-tooltip='true'>
        <template v-slot:default="scope">
        {{ scope.row.VALUE }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template v-slot:default="scope">
          <el-button type="text" @click="openDialogRuleFrom(scope.row)">配置</el-button>
          <el-button type="text" @click="resetRow(scope.row)">重置</el-button>
<!--          <el-popconfirm-->
<!--            @confirm="handleDelete(scope.$index, scope.row)"-->
<!--            confirm-button-text='确定'-->
<!--            cancel-button-text='我再看看'-->
<!--            icon="el-icon-info"-->
<!--            icon-color="red"-->
<!--            title="删除该行后，将不对表插入该字段的数据？"-->
<!--          >-->
<!--            <el-button slot="reference" type="text">删除</el-button>-->
<!--          </el-popconfirm>-->
        </template>
      </el-table-column>
    </el-table>
    <div class="text">共查询到{{ form.table.length }}个字段</div>
    <div v-if="btnShow" class="bottom_btn">
      <div class="btn_item fab-item-title firstBtn" @click="dialogImport=true">导出数据</div>
      <div class="btn_item fab-item-title secondBtn" @click="dialogMappingList=true">映射引用</div>
      <div class="btn_item fab-item-title thirdBtn" @click="saveMapping">
        <span v-if="mappingId">编辑映射</span>
        <span v-else>新建映射</span>
      </div>
      <div class="btn_item fab-item-title fourthBtn" @click="clickTableName(tableName)">重置</div>
    </div>
    <div class="optBtn">
      <el-button icon="el-icon-thumb" circle @click="btnShow = !btnShow" class="hand-btn"></el-button>
    </div>
    <import-dialog v-if="dialogImport" :dialogVisble="dialogImport" @closeDialog="dialogImport=false"
                   @importData="importData"></import-dialog>
    <RuleForm :visible.sync="dialogRuleFrom" :tables="tables" :dbInfo="dbInfo" :ruleOptions="ruleOptions"
              @updateRefreshKey="updateMainForm" :table="form.table" :row="row"
              @againRefreshReConfig="getReFakerConfig"></RuleForm>
    <MappingList :visible.sync="dialogMappingList" :id="dbInfo.id" :table="form.table" :ruleOptions="ruleOptions"
                 :reList="reList" @mappingObj="getMappingObj"
                 @updateRefreshKey="refreshKey = !refreshKey"></MappingList>
    <SaveMapping ref="saveMapping" :visible.sync="dialogMappingForm" :id="dbInfo.id" :table="form.table"></SaveMapping>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index'
import SaveMapping from './saveMappingForm'
import MappingList from './mappingList'
import RuleForm from './ruleForm'
import ImportDialog from './importDialog'
import {
  exportExcelApi,
  generateDataApi,
  getFieldByTableNameApi,
  ruleConfigFakerApi,
  ruleConfigReApi
} from '@/api/api'

export default {
  name: "OtherSide",
  props: ['tableName', 'dbInfo', "tables"],
  components: {Pagination, SaveMapping, MappingList, RuleForm, ImportDialog},
  data() {
    return {
      searchValue: "",
      btnShow: true,
      showMain: false,
      form: {
        table: [],
        number: 1,
      },
      row: "",
      ruleOptions: [],
      reList: [],
      dialogRuleFrom: false,
      dialogMappingList: false,
      dialogMappingForm: false,
      refreshKey: false,
      dialogImport: false,
      mappingId: "",
    }
  },
  created() {
    this.getReFakerConfig()
  },
  methods: {
    resetRow(ruleForm){
      for (const argument of this.form.table) {
        if (argument.COLUMN_NAME === ruleForm.COLUMN_NAME) {
          argument.isContact = ""
          argument.contactTable = ""
          argument.contactColumn = ""
          argument.FAKER = ""
          argument.VALUE = ""
          argument.params = ""
          argument.copyCurrentField = ""
          argument.isMapping = ""
          argument.mappingJson = ""
          argument.matchKey = ""
          argument.valueKey = ""
          argument.sqlText = ""
          argument.fileList = ""
          argument.fileName = ""
          argument.filePath = ""
        }
      }
      //重新渲染列表数据
      this.refreshKey = !this.refreshKey
    },

    saveMapping() {
      if (this.mappingId === '') {
        this.dialogMappingForm = true;
      } else {
        this.$confirm('确定保存当前所选择的映射配置吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.api({
            url: "/updateFieldMapping",
            method: "post",
            data: {id: this.mappingId, mapping: JSON.stringify(this.form.table)}
          }).then(resp => {
            this.$message({message: resp, type: 'success'})
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消编辑保存'
          });
        });
      }
    },

    getMappingObj(value) {
      console.log(JSON.parse(value).id)
      this.mappingId = JSON.parse(value).id
    },
    /*点击表名获取表字段*/
    async clickTableName(tableName) {
      //显示主体部分
      this.showMain = true
      const loading = this.$loading({
        lock: true, // lock的修改符--默认是false
        text: 'Loading', // 显示在加载图标下方的加载文案
        spinner: 'el-icon-loading', // 自定义加载图标类名
        background: 'rgba(0, 0, 0, 0.7)', // 遮罩层颜色
        target: document.querySelector('#table')//loading覆盖的dom元素节点
      })
      this.dbInfo["tableName"] = tableName
      this.form.table = await getFieldByTableNameApi(this.dbInfo)
      loading.close()
      this.mappingId = ""
    },

    /*获取faker的配置*/
    async getReFakerConfig() {
      this.ruleOptions = await ruleConfigFakerApi()
      let resp = await ruleConfigReApi({
        "pageNum": 1,
        "pageRow": 1000,
        "label": ""
      })
      this.reList = resp.list
    },

    /*配置完规则表单，渲染主页列表表单*/
    updateMainForm(ruleForm) {
      for (const argument of this.form.table) {
        if (argument.COLUMN_NAME === ruleForm.columnName) {
          argument.isContact = ruleForm.isContact
          argument.contactTable = ruleForm.contactTable
          argument.contactColumn = ruleForm.contactColumn
          argument.FAKER = ruleForm.ruleType
          argument.VALUE = ruleForm.defaultValue
          argument.params = ruleForm.params
          argument.copyCurrentField = ruleForm.copyCurrentField
          argument.isMapping = ruleForm.isMapping
          argument.mappingJson = ruleForm.mappingJson
          argument.matchKey = ruleForm.matchKey
          argument.valueKey = ruleForm.valueKey
          argument.sqlText = ruleForm.sqlText
          argument.fileList = ruleForm.fileList
          argument.fileName = ruleForm.fileName
          argument.filePath = ruleForm.filePath
        }
      }
      //重新渲染列表数据
      this.refreshKey = !this.refreshKey
    },

    /*打开子组件【规则配置】对话框*/
    openDialogRuleFrom(row) {
      this.row = row
      this.dialogRuleFrom = true
    },

    /*列表Faker,re显示的value转为label*/
    valueToLabel(status, parentValue, value) {
      let showValue = ""
      if (status === 1) {
        for (const valueElement of this.ruleOptions) {
          if (valueElement.value === parentValue) {
            showValue += valueElement.label;
            showValue += "/";
            for (let child of valueElement.children) {
              if(child.value === value){
                showValue += child.label;
              }
            }
          }
        }
      } else {
        for (const valueElement of this.reList) {
          // if (valueElement.value === value) {
          if (parentValue.indexOf(valueElement.value) !== -1) {
            console.log(123)
            showValue = valueElement.label
          }else{
            showValue = parentValue
          }
        }
      }
      return showValue
    },

    /*删除行代表该字段不作为新增数据的字段*/
    handleDelete(index, data) {
      this.form.table.splice(index, 1);
    },

    /*列表表头显示注释*/
    renderHeader(h, {column, $index}) {
      return h('span', [
        h('span', '默认值|re表达式'),
        h('el-tooltip', {props: {effect: 'dark', placement: 'top'}}, [
          h('div', {
              slot: 'content',
              attrs: {style: 'font-size: 14px; width: 500px; word-wrap:break-word;white-space: pre-line; line-height: 14px;'}
            },
            '1.未选择生成规则时，数据按默认值生成\n\n' +
            '2.字段不能为null时，必须选择生成规则或输入默认值\n\n' +
            '3.选择生成规则（正则表达式时），选择建议的re表达式或手动输入re表达式\n\n' +
            '4.选择生成规则（级联选择器只有一级）时，数据按生成规则生成\n\n' +
            '5.选择生成规则（级联选择器有二级）时，二级是String，默认值就输入字符串'),
          h('i', {class: 'el-icon-info', style: 'color:#409EFF;'})
        ])
      ])
    },

    /*导入数据弹框返回 导入的类型与数量*/
    importData(data) {
      this.form.number = data.number;
      if (data.type === "0") {
        this.onSubmit()
      } else {
        this.exportExcel()
      }
    },

    /*构造公共的form*/
    getPreForm(status) {
      let tables = []
      for (const table of this.form.table) {
        console.log(table)
        let a = {}
        let b = []
        a["COLUMN_NAME"] = table.COLUMN_NAME
        if (table.isContact === 1) {
          a["contactTable"] = table.contactTable
          a["contactColumn"] = table.contactColumn
          a["isContact"] = 1
          a["sqlText"] = table.sqlText = table.sqlText === undefined || table.sqlText === null ? "" : table.sqlText
        } else if (table.isContact === 0) {
          b.push(table.FAKER && table.FAKER.length > 1 ? table.FAKER[1].split("/")[0] : "")
          b.push(table.FAKER && table.FAKER.length > 1 ? table.FAKER[1].split("/")[1] : "")
          b.push(table.FAKER && table.FAKER.length > 2 ? table.FAKER[2]  : "")
          a["FAKER"] = b
          a["VALUE"] = table.VALUE ? table.VALUE : ""
          a["isContact"] = 0
          // a["VALUE"] = table.VALUE ? table.VALUE.indexOf("】") !== -1 ? table.VALUE.split("】")[1] : table.VALUE : ""
        } else if (table.isContact === 2) {
          a["copyCurrentField"] = table.copyCurrentField
          a["isMapping"] = table.isMapping
          a["mappingJson"] = table.mappingJson
          a["matchKey"] = table.matchKey
          a["valueKey"] = table.valueKey
          a["isContact"] = 2
        } else if (table.isContact === 3) {
          a["filePath"] = table.filePath
          a["isContact"] = 3
        } else {
          a["isContact"] = 4
        }
        //导入db
        if (status === 0) {
          if ((JSON.stringify(b).length !== 10 || a["VALUE"] !== "") && (table.isContact || table.isContact === 0)) {
            tables.push(a)
          }
          //导出execl
        } else {
          tables.push(a)
        }
      }
      let table
      table = {...this.form}
      table["dbInfo"] = this.dbInfo
      table["table"] = tables
      return table
    },

    /*导出Excel*/
    async exportExcel() {
      const loading = this.$loading({
        lock: true, // lock的修改符--默认是false
        text: 'Loading', // 显示在加载图标下方的加载文案
        spinner: 'el-icon-loading', // 自定义加载图标类名
        background: 'rgba(0, 0, 0, 0.7)', // 遮罩层颜色
        target: document.querySelector('#table')//loading覆盖的dom元素节点
      })
      let resp = await exportExcelApi(this.getPreForm(1))
      const link = document.createElement('a');
      let blob = new Blob([resp.data], {type: 'application/vnd.ms-excel'});
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      link.setAttribute('download', decodeURI(resp.headers["filename"]));
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      this.$message({message: "导出成功", type: 'success'})
      loading.close();
    },

    /*导入db*/
    async onSubmit() {
      const loading = this.$loading({
        lock: true, // lock的修改符--默认是false
        text: 'Loading', // 显示在加载图标下方的加载文案
        spinner: 'el-icon-loading', // 自定义加载图标类名
        background: 'rgba(0, 0, 0, 0.7)', // 遮罩层颜色
        target: document.querySelector('#table')//loading覆盖的dom元素节点
      })
      let resp = await generateDataApi(this.getPreForm(0))
      console.log(resp)
      if (resp.code !== "500") {
        this.$message({message: resp, type: 'success'})
      }
      loading.close()
    },
  }
}
</script>

<style lang="scss" scoped>
.table-content {
  .rule {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .text {
    padding: 10px 0 10px 0;
    color: #0044f0;
    font-size: 14px;
  }

  .bottom_btn {
    position: fixed;
    bottom: 28px;
    right: 80px;

    .firstBtn {
      color: rgb(245, 108, 108);
      background: rgb(252, 241, 241);
    }

    .secondBtn {
      color: rgb(0, 128, 128);
      background: rgb(235, 242, 242);
    }

    .thirdBtn {
      color: rgb(2, 167, 240);
      background: rgb(244, 244, 245);
    }

    .fourthBtn {
      color: rgb(103, 194, 58);
      background: rgb(242, 249, 238);
    }

    .fifthBtn {
      color: rgb(230, 162, 60);
      background: rgb(252, 246, 238);
    }

    .fab-item-title {
      cursor: pointer;
      box-shadow: 0 1px 0.5px #ccc;
      padding: 5px 5px;
      font-size: 14px;
      min-width: 5em;
      white-space: nowrap;
      border-radius: 2px;
      text-align: center;
      display: inline-block;
    }
  }

  .optBtn {
    position: fixed;
    right: 40px;
    color: #FFF;
    bottom: 26px;

    .hand-btn {
      background-color: #0044f0 !important;
      border-color: #0044f0 !important;
      color: white;
    }
  }
}
</style>
